package cn.dinghu.pro.controller;


import cn.dinghu.pro.common.ResultData;
import cn.dinghu.pro.entity.Admin;
import cn.dinghu.pro.entity.User;
import cn.dinghu.pro.service.IAdminService;
import cn.dinghu.pro.utils.CodeUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.Authorization;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * <p>
 * 管理员表 前端控制器
 * </p>
 *
 * @author dinghu
 * @since 2025-10-14
 */
@RestController
@RequestMapping("/admin")
@Api(tags = "后台用户管理")
@CrossOrigin
@ApiSupport(author = "熙神" )
public class AdminController {
    @Autowired
    private IAdminService adminService;

    @PostMapping("/login")
    @ApiOperation(value = "用户登录并返回对象",notes = "登录功能")
    public ResultData<Admin> login(HttpServletRequest req, @RequestParam String yzm,
                                  @RequestParam String username, @RequestParam String password) {
        // 从application中取到存的code比对 验证验证码
        ServletContext application = req.getServletContext();
        String sessionCode = application.getAttribute("code").toString();

        if(StringUtils.isNotBlank(yzm)){
            // 大小写转换后比对，方便用户输入，减少用户问候
            if (!yzm.equalsIgnoreCase(sessionCode)) {
                return ResultData.error("验证码输入错误或无效！");
            }
        }else{
            return ResultData.error("请输入验证码！");
        }
        Admin admin = adminService.login(username,password);
        if(null != admin){
            application.setAttribute("admin",admin);
            return ResultData.ok(admin);
        }else{
            return ResultData.error("用户名或密码错误！");
        }
    }

    @GetMapping("queryById/{id}")
    @ApiOperation(value = "查询用户",notes = "使用mp实现")
    public ResultData queryById(@PathVariable Integer id){
        Admin admin = adminService.getById(id);
        return null !=admin?ResultData.ok(admin):ResultData.error();
    }

    @GetMapping("/yzm")
    @ApiOperation(value = "获取验证码",notes = "验证码功能")
    public void yzm(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Map<String,Object> codeMap = CodeUtil.generateCodeAndPic();
        ServletContext application = req.getServletContext();
        application.setAttribute("code",codeMap.get("code").toString());

        // 禁止图像缓存
        resp.setHeader("Pragma", "no-cache");
        resp.setHeader("Cache-Control", "no-cache");
        resp.setDateHeader("Expires", -1);
        resp.setContentType("image/jpeg");

        // 将图像输出到Servlet输出流中，此处因为是IO流，不能使用json格式化
        ServletOutputStream sos;
        try {
            sos = resp.getOutputStream();
            ImageIO.write(((java.awt.image.BufferedImage) codeMap.get("codePic")) , "jpeg", sos);
            sos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @PostMapping("/logout")
    @ApiOperation(value = "用户退出登录",notes = "退出登录功能")
    public ResultData logout(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        ServletContext application = req.getServletContext();
        application.removeAttribute("admin");
        return ResultData.ok();
    }
}
